import {
  request
} from '../../request/index'
import regeneratorRuntime, { async } from '../../lib/runtime/runtime'
let isSend = false

Page({

  data: {
    placeholderContent: "",
    hotList: [],
    searchContent: "",
    searchList: [],
    historyList:[]
  },

  onLoad: function (options) {
    this.getInitData()
    this.getHotList()
    this.getSearchHistory()
  },
  //获取默认搜索
  async getInitData() {
    let {
      data: {
        data
      }
    } = await request({
      url: "/search/default"
    })
    this.setData({
      placeholderContent: data.showKeyword
    })
  },
  //获取热搜列表
  async getHotList() {
    let {
      data: {
        data
      }
    } = await request({
      url: "/search/hot/detail"
    })
    this.setData({
      hotList: data
    })

  },

  getSearchHistory(){
    let historyList = wx.getStorageSync('searchHistory');
    if(historyList){
      this.setData({
        historyList
      })
    }
  },
  //搜索匹配
  handleInputChange(e) {
    this.setData({
      searchContent: e.detail.value.trim()
    })
    if(isSend){
      return
    }
    isSend = true
    this.getSearchListData()
    setTimeout(() => {
      isSend = false
    }, 600)
    
  },
  //获取搜索数据
  async getSearchListData(){
    if(!this.data.searchContent){
      this.setData({
        searchList:[]
      })
      return
    }

    let {searchContent,historyList} = this.data

    let {
      data
    } = await request({
      url: "/search",
      data: {
        keywords: this.data.searchContent,limit:10
      }
    })
    this.setData({
      searchList: data.result.songs
    })

    if(historyList.indexOf(searchContent) !== -1){
      historyList.splice(historyList.indexOf(searchContent),1)
    }
    historyList.unshift(searchContent)
    this.setData({
      historyList
    })
    wx.setStorageSync('searchHistory', historyList);
  },

  //清空搜索内容
  clearSearch(){
    this.setData({
      searchContent:"",
      searchList:[]
    })
  },
  //清空搜素历史记录
  deleteSearch(){
    
    wx.showModal({
      title: '确定要清空历史记录吗？',
      content: '',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: (result) => {
        if(result.confirm){
          this.setData({
            historyList:[]
          })
          wx.removeStorageSync("searchHistory");
        }
      },
    });
  },
  toList(e){
    let {name} = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/searchList/index?name='+name
    });
  },

  toList1(e){
    console.log(e);
    let name = e.detail.value
    wx.navigateTo({
      url: '/pages/searchList/index?name='+name
    });
  }

})